import { App } from 'vue'
import { logger, eventBus } from '@/instance'

const stateMap = new Map<string, any>()

export default {
  install(app: App, opt: any) {
    app.directive('ui-state', {
      /**
       * 注册mouse相关事件并修改绑定的数据
       *
       * @param {*} el
       * @param {*} binding
       */
      mounted(el: any, binding) {
        const data = binding.value.data
        const prefix = binding.value.prefix
        logger.log('plugins/ui-state', 'ui-state mounted', arguments)
        el.onmouseenter = () => (data.hovering = true)
        el.onmouseleave = () => (data.hovering = false)
        el.onmousedown = () => {
          data.operating = true
          window.addEventListener(
            'mouseup',
            () => {
              data.operating = false
            },
            {
              once: true,
            }
          )
        }
        el.onmouseup = () => {
          const key = `${prefix}_mouseup`
          const last = stateMap.get(key)
          if (last) {
            last.selected = false
          }
          data.selected = true
          stateMap.set(key, data)
        }
      },
      beforeUnmount(el: any) {
        logger.log('plugins/ui-state', 'drag before unmounted', arguments)
        ;['mouseenter', 'mouseleave', 'mousedown', 'mouseup'].forEach((t) => {
          el['on' + t] = null
        })
      },
    })
  },
}
